//
// Created by LiuYou on 2021/8/3.
//
/*
 字符串字面值

 为字符串变量赋值

 */

#include <cstdlib>
#include <cstdio>
#include <cstring>


static void replaceBlank(char* str, int len) {
    if (str == nullptr || len <= 0) {
        return;
    }
    // originalLength为字符串str的实际长度
    int originalLength = 0;
    int numberOfBlank = 0;
    int i = 0;
    while (str[i] != '\0') {
        ++originalLength;
        if (str[i] == ' ') {
            ++numberOfBlank;
        }
        ++i;
    }
    /*
         originalLength: 13
         numberOfBlank: 2
     */
    fprintf( stdout, "originalLength: %d\n", originalLength );
    fprintf( stdout, "numberOfBlank: %d\n", numberOfBlank );
    {
        // 这是获取空格的数量的另一种方法。
        int blankCount = 0;
        for (int i = 0; i < len; ++i) {
            if (str[i] == ' ') {
                ++blankCount;
            }
        }
        fprintf( stdout, "blankCount: %d\n", blankCount );
    }

    // newLength为把空格替换成 %20 之后的长度
    int newLength = originalLength + numberOfBlank * 2;
    if (newLength > len) {
        return;
    }
    int indexOfOriginal = originalLength;
    int indexOfNew = newLength;
    while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) {
        if (str[indexOfOriginal] == ' ') {
            str[indexOfNew--] = '0';
            str[indexOfNew--] = '2';
            str[indexOfNew--] = '%';
        } else {
            str[indexOfNew--] = str[indexOfOriginal];
        }
        --indexOfOriginal;
    }
//    fprintf( stdout, "str: \"%s\"", str );
}


/*
 * 5. 替换空格
 */
int main() {

    {
        char string[20]{"ni hao !"};
        // 有19个字符, 但是数组需要20个。
        strcpy( string, "i love cpp forever!" );

        fprintf( stdout, "string: %s\n", string );
    }

    char string[100]{"we are happy."};
    size_t sizeofString = sizeof( string ) / sizeof( char );
    int byteLen = static_cast<int>(sizeofString);
    fprintf( stdout, "string: \"%s\", size: %lu\n", string, sizeofString );
    replaceBlank( string, byteLen );
    fprintf( stdout, "string: \"%s\", size: %lu\n", string, sizeofString );


    exit( 0 );
}